import {
    request,
    summary,
    body,
    tags,
    middlewares,
    path,
    prefix,
    security,
    description,
    responses
} from 'koa-swagger-decorator';
import Headers from '../middleware/Headers';
const tag = tags(['用户相关']);
//解析token
const tools = require('../util/jwt')
import {
    successfn,
    abnormalfn,
    expfn
} from "../util/status"
import _ from "lodash"
//引入数据表模型
const model = require('../database/model');
const UserInfo = model.UserInfo
// 关联用户表
UserInfo.belongsTo(model.User, {
    foreignKey: 'user_id',
    targetKey: 'id'
})
if(process.env.NODE_INIT==='true'){
    UserInfo.sync({
        force: true,//是否清空数据库表
    }).then(function() {
        console.log('ok');
    });
}
const userSchema = {
    birthday: {
        type: 'string',
        required: false,
        example: '1980-01-01',
        description: "出生日期"
    },
    nickname: {
        type: 'string',
        required: false,
        example: 'bill',
        description: "昵称"
    },
    tags: {
        type: 'Array',
        required: false,
        example: ['读书'],
        description: "标签"
    }
};

//数据库操作类
class userInfoModule {
    static async userInfoRegist(data) {
        console.log(data)
        return await UserInfo.create({
            user_id: data.user_id,
            birthday: data.birthday,
            nickname: data.nickname,
            tags: data.tags
        })
    }

    static async getUserInfo(user_id) {
        return await UserInfo.findOne({
            where: {
                user_id
            }
        })
    }

    static async userInfoUpdate(data) {
        console.log(data)
        return await UserInfo.update(data)
    }

}

//功能处理
@prefix('/user')
export default class userInfoController {
    //注册用户
    @request('POST', '/addUserInfo')
    @summary('新增用户信息')
    // @description('example of api')
    @tag
    @middlewares(Headers())
    @body(userSchema)
    @responses({
        200: {
            description: 'success',
            "schema": {
                "type": "object",
                "items": {
                    // $ref: "#/definitions/user"
                }
            }
        }
    })
    static async create(ctx) {
        const req = ctx.validatedBody;
        const token = ctx.headers.authorization
        const result = await tools.verToken(token);
        const user_id = result.user_id
        if (req.birthday && req.nickname) {
            try {
                const query = await userInfoModule.getUserInfo(user_id);
                if (query) {
                    ctx.body = abnormalfn({
                        msg: "信息已存在，请勿重新创建"
                    });
                } else {
                    const param = {
                        birthday: req.birthday,
                        nickname: req.nickname,
                        user_id,
                        tags: _.isArray(req.tags) ? JSON.stringify(req.tags) : null
                    }

                    const data = await userInfoModule.userInfoRegist(param);

                    ctx.body = successfn({
                        msg: "用户信息添加成功",

                    })

                }

            } catch (error) {
                ctx.body = abnormalfn({
                    msg: "参数不齐全"
                })
            }
        }
    }

    //更改用户信息
    @request('POST', '/updateUserInfo')
    @summary('更改用户信息')
    // @description('example of api')
    @tag
    @middlewares(Headers())
    @body(userSchema)
    @responses({
        200: {
            description: 'success',
            "schema": {
                "type": "object",
                "items": {
                    // $ref: "#/definitions/user"
                }
            }
        }
    })
    static async update(ctx) {
        const req = ctx.validatedBody;
        
        const token = ctx.headers.authorization
        const result = await tools.verToken(token);
        const user_id = result.user_id
        try {
            let param = Object.keys(req).reduce((c,t) => {
                if (t === "tags") {
                    c[t] = _.isArray(req.tags) ? JSON.stringify(req.tags) : null
                } else c[t] = req[t]
                return c
            }, {})

            const data = await UserInfo.update(param, {
                'where': {
                    user_id
                }
            })

            ctx.body = successfn({
                msg: "用户信息更新成功",

            })



        } catch (error) {
            ctx.body = abnormalfn({
                msg: "参数不齐全"
            })
        }

    }
}